#include "mainwindow.h"
#include <QApplication>
#include <QVBoxLayout>
#include <QDebug>
#include <QImage>
#include <QPixmap>
#include <QPalette>
#include <QLinearGradient>

MainWindow::MainWindow(QWidget *parent)
    : QWidget(parent)
    , manager(new QNetworkAccessManager(this))
{
    setWindowTitle("Weather App");
    setFixedSize(400,500);

    QPalette palette;
    QLinearGradient gradient(0,0,0,height());
    gradient.setColorAt(0,QColor(135,206,235));
    gradient.setColorAt(1,QColor(255,255,255));
    palette.setBrush(QPalette::Background,gradient);
    setPalette(palette);

    gifLabel=new QLabel(this);
    gifLabel->setFixedSize(375,275);
    QMovie *movie=new QMovie("D:\\qt-projects\\Loginer\\5123.gif_wh300.gif");
    gifLabel->setMovie(movie);
    gifLabel->setAlignment(Qt::AlignCenter);
    movie->start();

    cityInput=new QLineEdit(this);
    cityInput->setPlaceholderText("请输入需要查询的城市名称...");
    cityInput->setStyleSheet("QPushButton { font-size: 16px; padding: 10px; background-color: #4CAF50; color: white; border: none; border-radius: 5px; }"
                               "QPushButton:hover { background-color: #45a049; }");

    fetchButton = new QPushButton("获取天气信息", this);
    fetchButton->setStyleSheet("QPushButton { font-size: 16px; padding: 10px; background-color: #4CAF50; color: white; border: none; border-radius: 5px; }"
                               "QPushButton:hover { background-color: #45a049; }");

    weatherInfo=new QLabel(this);
    weatherInfo->setStyleSheet(
        "QLabel { "
        "font-size: 18px; "
        "color: #222; "
        "padding: 10px; "
        "text-align: center; "
        "}");
    weatherInfo->setWordWrap(true);
    weatherInfo->setAlignment(Qt::AlignCenter);

    weatherIcon = new QLabel(this);
    weatherIcon->setAlignment(Qt::AlignCenter);

    QVBoxLayout *layout = new QVBoxLayout();
    layout->addWidget(gifLabel);
    layout->addWidget(cityInput);
    layout->addWidget(fetchButton);
    layout->addWidget(weatherInfo);

    setLayout(layout);
    connect(fetchButton,&QPushButton::clicked,this,&MainWindow::fetchWeather);
}

MainWindow::~MainWindow()
{
}

void MainWindow::fetchWeather(){
    QString city=cityInput->text().trimmed();
    if(city.isEmpty()){
        weatherInfo->setText("请输入需要查询的城市名！");
        return ;
    }
    QString apiKey = "df97ebfa83cd73cec8cd0efa08c749bb";  // Your API key
    QString url = QString("https://api.openweathermap.org/data/2.5/weather?q=%1&appid=%2&units=metric")
                      .arg(city, apiKey);
    QUrl requestUrl(url);
    if(!requestUrl.isValid()){
        weatherInfo->setText("Url不合法！");
        return ;
    }

    QNetworkRequest request(requestUrl);
    manager->get(request);
    connect(manager,&QNetworkAccessManager::finished,this,&MainWindow::handleReply);
}

void MainWindow::handleReply(QNetworkReply *reply){
    if(reply->error()==QNetworkReply::NoError){
        QByteArray responseData=reply->readAll();
        QJsonDocument jsonDoc=QJsonDocument::fromJson(responseData);
        QJsonObject jsonObj=jsonDoc.object();

        if(jsonObj.contains("weather")&&jsonObj.contains("main")){
            QString weatherDesc=jsonObj["weather"].toArray().first().toObject()["description"].toString();
            double temperture=jsonObj["main"].toObject()["temp"].toDouble();
            double humidity=jsonObj["main"].toObject()["humidity"].toDouble();
            QString iconCode=jsonObj["weather"].toArray().first().toObject()["icon"].toString();

            weatherInfo->setText(
                QString("<b>Weather:</b> %1<br>"
                        "<b>Temperature:</b> %2 C<br>"
                        "<b>Humidity:</b> %3%")
                .arg(weatherDesc)
                .arg(temperture)
                .arg(humidity));

            QString iconUrl = QString("http://openweathermap.org/img/wn/%1.png").arg(iconCode);
            QPixmap pixmap;
            pixmap.load(iconUrl);
            weatherIcon->setPixmap(pixmap.scaled(100,100,Qt::KeepAspectRatio));
        }else{
            weatherInfo->setText("Invalid response from API.");
        }
    }else{
        weatherInfo->setText("Failed to fetch weather information.<br>Error: " + reply->errorString());
    }
    reply->deleteLater();
}
